package ck.android.englishschool.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;


public class BrHttpManager {

	public final String TAG = "BrHttpManager";
	private static BrHttpManager instance = null;
	
	public synchronized static BrHttpManager getInstance() {
		if (instance == null) {
			synchronized (BrHttpManager.class) {
				if (instance == null) {
					instance = new BrHttpManager();
				}
			}
		}
		return instance;
	}
	
	/**
	 * http 객체 가져오기
	 * @param urladdr
	 * @return
	 */
	public HttpRequestor getHttpRequestor(String urladdr){
		HttpRequestor upload = null;
		try {
			upload = new HttpRequestor(new URL(urladdr));	
		} catch (Exception e) {
			e.printStackTrace();
		}
		return upload;
	}
	
	/**
	 * send post
	 * @param upload
	 */
	public InputStream SendHttpPost(HttpRequestor upload){
		InputStream input = null;
		try {
			input = upload.sendPost();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return input;
	}
	
	/**
	 * send multipart post
	 * @param upload
	 * @return
	 */
	public InputStream SendMutilPartPost(HttpRequestor upload){
		InputStream input = null;
		try {
			input = upload.sendMultipartPost();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return input;
	}

	/**
	 * upload 데이터 추가
	 * @param upload
	 * @param key
	 * @param value
	 */
	public void AddParameter(HttpRequestor upload, String key,String value){
		try {
			upload.addParameter(key, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * upload 파일 데이터 추가
	 * @param upload
	 * @param key
	 * @param fileaddr
	 */
	public void AddFileParameter(HttpRequestor upload, String key, String fileaddr){
		try {
			upload.addFile(key, new File(fileaddr));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String ResultToJson(InputStream is) {
	       
	      String data = null;
	      StringBuilder builder = new StringBuilder();
	      try {
	         BufferedReader br = new BufferedReader(new InputStreamReader(is));
	         for (;;) {
	            String line = br.readLine();
	            if (line == null)
	               break;
	            builder.append(line);
	         }
	         br.close();
	         
	      } catch (IOException e) {
	         e.printStackTrace();
	      }
	      return builder.toString();
	   } 
}
